#include <driver/uart.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <driver/gpio.h>
#include <esp_log.h>

static const int uart_buffer_size = (1024 * 2);
static const uart_port_t uart_num = UART_NUM_1;
static const gpio_num_t tx = GPIO_NUM_20;
static const gpio_num_t rx = GPIO_NUM_21;

int uart1_write_bytes(const char *fmt, va_list args) {
    char buf[256];                              // 临时缓冲区
    int len = vsnprintf(buf, sizeof(buf), fmt, args);  // 格式化日志
    uart_write_bytes(UART_NUM_1, buf, len);     // 发送到 UART1
    return len;                                 // 返回写入长度
}

void uart_task(void* params){
    while (1) {
        uint8_t data;
        if (uart_read_bytes(uart_num, &data, 1, pdMS_TO_TICKS(100)) > 0) {
            // Echo the received data back
            uart_write_bytes(uart_num, &data, 1);
        }
        vTaskDelay(pdMS_TO_TICKS(5000));
    }
}

void init_uart() {
    ESP_ERROR_CHECK(uart_driver_install(uart_num, uart_buffer_size, uart_buffer_size, 0, NULL, 0));
    ESP_ERROR_CHECK(uart_set_pin(uart_num, tx, rx, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));

    uart_config_t uart_config = {
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS,
        .rx_flow_ctrl_thresh = 122,
    };
    ESP_ERROR_CHECK(uart_param_config(uart_num, &uart_config));

    // 重定向 ESP_LOG 到 UART1
    // printf("Redirecting ESP_LOG to UART1\n");
    // ESP_LOGI("UART", "UART initialized on TX=%d, RX=%d", tx, rx);
    // esp_log_set_vprintf(uart1_write_bytes);
    // ESP_LOGI("UART", "UART test log after redirection");
    // xTaskCreate(uart_task, "uart_task", 2048, NULL, 10, NULL);
}